package com.cxria.problem.utils

import com.fasterxml.jackson.core.JsonGenerator
import com.fasterxml.jackson.core.JsonParser
import com.fasterxml.jackson.databind.*
import com.fasterxml.jackson.databind.module.SimpleModule
import org.springframework.stereotype.Component

import java.sql.Timestamp
import java.time.Instant
import java.time.LocalDateTime
import java.time.ZoneId

@Component
class MyObjectMapper extends ObjectMapper {

	MyObjectMapper() {
		SimpleModule module = new SimpleModule()
		module.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer())
		module.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer())
		this.registerModule(module)
		this.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false)
	}

	class LocalDateTimeSerializer extends JsonSerializer<LocalDateTime> {
		@Override
		void serialize(LocalDateTime value, JsonGenerator jgen, SerializerProvider provider){
			jgen.writeNumber(Timestamp.valueOf(value).getTime())
		}
	}

	class LocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> {
		@Override
		LocalDateTime deserialize(JsonParser jsonParser, DeserializationContext deserializationContext){
			long timestamp = jsonParser.getValueAsLong()
			Date date = new Date(timestamp)
			Instant instant = date.toInstant()
			ZoneId zoneId = ZoneId.systemDefault()
			LocalDateTime localDateTime = instant.atZone(zoneId).toLocalDateTime()
			localDateTime
		}
	}

}

